import type { DailyModel } from '@/model/DailyModel'

const SHORT_TIME = 12
const LONG_TIME = 26
const MID = 9

export function calcMACD(dailyList: Array<DailyModel>) {
  const macdList: Array<number> = []
  const difList = calDif(dailyList)
  const deaList = calDea(difList)
  dailyList.forEach((value, index) => macdList.push((difList[index] - deaList[index]) * 2))
  return macdList
}

export function calDif(dailyList: Array<DailyModel>) {
  const difList: Array<number> = []
  const emaShort: Array<number> = calEma(SHORT_TIME, dailyList)
  const emaLong: Array<number> = calEma(LONG_TIME, dailyList)
  dailyList.forEach((value, index) => difList.push(emaShort[index] - emaLong[index]))
  return difList
}

export function calDea(difList: Array<number>) {
  const dea: Array<number> = []
  const a = 2.0 / (MID + 1)
  dea.push(difList[0])
  difList.filter((value, index) => index !== 0)
    .forEach((value, index) => dea.push(a * value + (1 - a) * dea[index]))
  return dea
}

function calEma(dayCount: number, dailyList: Array<DailyModel>) {
  const ema: Array<number> = []
  const a = 2.0 / (dayCount + 1)
  ema.push(dailyList[0].close)
  dailyList.filter((value, index) => index !== 0)
    .forEach((daily, index) => ema.push(a * daily.close + (1 - a) * ema[index]))
  return ema
}
